package com.ihr360.expr.operator;

import com.ihr360.expr.ExprBigDecimal;
import com.ihr360.expr.ExprDouble;
import com.ihr360.expr.ExprException;
import com.ihr360.expr.core.AbstractMathematicalOperator;
import com.ihr360.expr.core.Expr;
import com.ihr360.expr.core.ExprType;

import java.math.BigDecimal;

/**
 * 四则运算减法
 */
public class ExprSubtraction extends AbstractMathematicalOperator
{
    public ExprSubtraction(Expr lhs, Expr rhs) {
        super(ExprType.Subtraction, lhs, rhs);
    }

    @Override
    protected Expr evaluate(double lhs, double rhs) throws ExprException {
        return new ExprDouble(BigDecimal.valueOf(lhs).subtract(BigDecimal.valueOf(rhs)).doubleValue());
    }

    @Override
    protected Expr evaluate(BigDecimal lhs, BigDecimal rhs) throws ExprException {
        return new ExprBigDecimal(lhs.subtract(rhs));
    }

    @Override
    public void validate() throws ExprException {
        if (rhs == null){
            throw new ExprException("RHS of operator missing");
        }
    }

    @Override
    public String toString() {
        if (lhs == null){
            return "-" + rhs;
        }
        else{
            return lhs + "-" + rhs;
        }
    }
}
